package com.hdw.cms.controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.hdw.basic.model.SystemContext;
import com.hdw.cms.auth.AuthClass;
import com.hdw.cms.auth.AuthMethod;
import com.hdw.cms.dto.AjaxObj;
import com.hdw.cms.dto.TopicDto;
import com.hdw.cms.model.Attachment;
import com.hdw.cms.model.Channel;
import com.hdw.cms.model.ChannelTree;
import com.hdw.cms.model.ChannelType;
import com.hdw.cms.model.Topic;
import com.hdw.cms.model.User;
import com.hdw.cms.service.AttachmentService;
import com.hdw.cms.service.ChannelService;
import com.hdw.cms.service.GroupService;
import com.hdw.cms.service.IndexService;
import com.hdw.cms.service.KeywordService;
import com.hdw.cms.service.TopicService;
import com.hdw.cms.utils.JsonUtil; 
@RequestMapping("/admin/topic")
@Controller("topicController")
@AuthClass("login")//登录用户可能访问
public class TopicController {

	private final static List<String> imgTypes = Arrays.asList("jpg", "jpeg",
			"gif", "png", "JPG");
	private final static List<String> videoTypes = Arrays.asList("rm", "rmvb",
			"flv", "mp4", "avi", "mpeg", "wmv", "asf");

	@Resource(name = "attachmentService")
	private AttachmentService attachmentService;

	@Resource(name = "topicService")
	private TopicService topicService;

	@Resource(name = "channelService")
	private ChannelService channelService;

	@Resource(name = "keywordService")
	private KeywordService keywordService;


	@Resource(name = "indexService")
	private IndexService indexService;

	@Resource(name = "groupService")
	private GroupService groupService;

	private void initList(String con, Integer cid, Model model,
			HttpSession session, Integer status) {
		SystemContext.setSort("t.publishDate");
		SystemContext.setOrder("desc");
		boolean isAdmin = (Boolean) session.getAttribute("isAdmin");
		if (isAdmin) {
			model.addAttribute("datas", topicService.find(cid, con, status));
		} else {
			User loginUser = (User) session.getAttribute("loginUser");
			model.addAttribute("datas",
					topicService.find(loginUser.getId(), cid, con, status));
		}
		if (con == null)
			con = "";
		SystemContext.removeOrder();// 移除顺序
		SystemContext.removeSort();// 移除排序
		model.addAttribute("con", con);
		model.addAttribute("cid", cid);
		model.addAttribute("cs", channelService.listPublishChannel());
	}

	// 已发布审核过的文章
	@RequestMapping("/audits.do")
	public String auditList(@RequestParam(required = false) String con,
			@RequestParam(required = false) Integer cid, Model model,
			HttpSession session) {
		initList(con, cid, model, session, 1);
		return "topic/list";
	}

	// 产品start
	@AuthClass("login")
	@RequestMapping("/product.do")
	public String productList(Model model, HttpSession session) {
		List<Channel> channel=channelService.listChannelByType(ChannelType.TOPIC_PROIMG);
		if(channel.size()>0){
		return "redirect:/admin/topic/showPic/" + channel.get(0).getId()+".do";
		}
		else{
			return "redirect:/admin/topic/showPic/0.do";
		}
	}

	@RequestMapping("/showPic/{proTypeId}.do")
	public String showPic(@PathVariable Integer proTypeId, Model model) {
		List<Attachment> al=attachmentService.listVideoAndPro();
		for(Attachment a:al)
		{
			attachmentService.updatePath(a);
		}
		List<Topic> tl=topicService.ListAllTopic();
		for(Topic t:tl)
		{
			topicService.updateContent(t);
		}
		List<Channel> channel=channelService.listChannelByType(ChannelType.TOPIC_PROIMG);
		SystemContext.setPageSize(6);
		SystemContext.setSort("a.proPos");
		SystemContext.setOrder("asc");
		model.addAttribute("proPic", attachmentService.findProPic(proTypeId));
		model.addAttribute("product", channel);
		model.addAttribute("proTypeId", proTypeId);
		model.addAttribute("maxPos", attachmentService.getMinAdnMaxProPos().get("max"));
		model.addAttribute("minPos", attachmentService.getMinAdnMaxProPos().get("min"));
		return "product/list";
	}

	@RequestMapping(value = "/addProPic.do", method = RequestMethod.GET)
	public String proPicAdd(Model model) {
		List<Channel> channel=channelService.listChannelByType(ChannelType.TOPIC_PROIMG);
		model.addAttribute("product", channel);
		return "product/addPic";
	}
	
	@RequestMapping(value="/updatePic/{id}.do",method = RequestMethod.GET)
	public String updatePic(@PathVariable int id,Model model){
		Attachment pic=attachmentService.load(id);
		Channel c=channelService.load(pic.getProTypeId());
		List<Channel> product=channelService.listChannelByType(ChannelType.TOPIC_PROIMG);
		pic.setattName(pic.getattName().trim());
		model.addAttribute("pic", pic);
		model.addAttribute("c", c);
		model.addAttribute("product", product);
		return "product/updatePic";
	}
	// 产品end
	//video start
	@RequestMapping(value = "/video.do")
	public String video(Model model) {
		List<Channel> videoChannel = channelService.listChannelByType(ChannelType.VIDEO_LIST);
		if(videoChannel.size()>0){
		return "redirect:/admin/topic/showVideo/" + videoChannel.get(0).getId()+".do";}
		else{
			return "redirect:/admin/topic/showVideo/0.do";
		}
	}

	@RequestMapping(value = "/showVideo/{id}.do")
	public String showVideo(Model model, @PathVariable Integer id) {
		List<Channel> videoChannel =channelService.listChannelByType(ChannelType.VIDEO_LIST);
		SystemContext.setPageSize(12);
		SystemContext.setSort("a.vdoPos");
		SystemContext.setOrder("asc");
		model.addAttribute("video", attachmentService.findVideo(id));
		model.addAttribute("videoChannel", videoChannel);
		model.addAttribute("videoId", id);
		model.addAttribute("maxPos", attachmentService.getMinAdnMaxVdoPos().get("max"));
		model.addAttribute("minPos", attachmentService.getMinAdnMaxVdoPos().get("min"));
		return "video/list";
	}

	@RequestMapping(value = "/addVideo.do", method = RequestMethod.GET)
	public String proVideo(Model model) {
		List<Channel> videoChannel = channelService.listChannelByType(ChannelType.VIDEO_LIST);
		model.addAttribute("videoChannel", videoChannel);
		return "video/addVideo";
	}

	@RequestMapping(value="/updateVideo/{id}.do",method = RequestMethod.GET)
	public String updateVideo(@PathVariable int id,Model model){
		Attachment video=attachmentService.loadVideo(id);
		Channel c=channelService.load(video.getProTypeId());
		List<Channel> videoType=channelService.listChannelByType(ChannelType.VIDEO_LIST);
		video.setattName(video.getattName().trim());
		model.addAttribute("video", video);
		model.addAttribute("c", c);
		model.addAttribute("videoType",videoType);
		return "video/updateVideo";
	}
	@RequestMapping(value="/updateVideo.do",method = RequestMethod.GET)
	public String updateVideo1(){
		return "video/updateVideo";
	}
	// 已发布未审核过的文章
	@RequestMapping("/unaudits.do")
	public String unauditList(@RequestParam(required = false) String con,
			@RequestParam(required = false) Integer cid, Model model,
			HttpSession session) {
		initList(con, cid, model, session, 0);
		return "topic/list";
	}

//	 审核文章
	 @RequestMapping("/changeStatus/{id}.do")
	 public String changeStatus(@PathVariable int id, Integer status) {
	 topicService.updateStatus(id);
	 indexService.generateBody();
	 if (status == 0) {
	 return "redirect:/admin/topic/unaudits.do";
	 } else {
	 return "redirect:/admin/topic/audits.do";
	 }
	 }

	// 上传处理
	@RequestMapping(value = "/upload.do", method = RequestMethod.POST)
	// 返回的是json类型的值，而uploadify只能接受字符串
	public void upload(MultipartFile attach, HttpServletResponse resp,
			String attTypeId, String videoId) throws IOException {
		resp.setContentType("text/plain;charset=utf-8");
		AjaxObj ao = null;
		String oldName = FilenameUtils
				.getBaseName(attach.getOriginalFilename());
		try {
			// 新建附件对象
			Attachment att = new Attachment();
			// 获取文件扩展名
			String ext = FilenameUtils.getExtension(attach
					.getOriginalFilename());
			// System.out.println(ext);
			// 判断是否是图片类型，是图片类型设置为1，不是设置为0
			if (imgTypes.contains(ext)) {
				if (videoId == null || "".equals(videoId)) {
					att.setisProImg(1);
					att.setProTypeId(Integer.parseInt(attTypeId));
				} else {
					att.setIsVideoImg(1);
					att.setVideoId(Integer.parseInt(videoId));
				}
			} 
			if (videoTypes.contains(ext)) {
				att.setIsVideo(1);
				att.setProTypeId(Integer.parseInt(attTypeId));
			} 
			att.setattName(oldName);
			att.setIsIndexPic(0);
			// 根据当前日期命名为新文件名
			att.setNewName(String.valueOf(new Date().getTime()) + "." + ext);
			att.setOldName(oldName);
			att.setSuffix(ext);
			att.setType(attach.getContentType());
			att.setSize(attach.getSize());
			// 把处理好的图片传到业务逻辑层处理
			attachmentService.add(att, attach.getInputStream());
			ao = new AjaxObj(1, null, att);
		} catch (IOException e) {
			ao = new AjaxObj(0, e.getMessage());
		}
		resp.getWriter().write(JsonUtil.getInstance().obj2json(ao));
	}
	@RequestMapping("/delete/{id}.do")
	public String delete(@PathVariable int id, Integer status) {
		topicService.delete(id);
//		if (topicService.isUpdateIndex(t.getChannel().getId())) {
//			indexService.generateNewpic();
//			indexService.generateBody();
//		}
		indexService.generateBody();
		if (status == 0) {
			return "redirect:/admin/topic/unaudits.do";
		} else {
			return "redirect:/admin/topic/audits.do";
		}
	}

	@RequestMapping("/delpic/{id}.do")
	public String delpic(@PathVariable int id) {
		int tid=attachmentService.load(id).getProTypeId();
		attachmentService.delete(id);
		indexService.generateBody();
		return "redirect:/admin/topic/showPic/"+tid+".do";
	}
	@RequestMapping("/delvdo/{id}/{iid}.do")
	public String delvdo(@PathVariable int id,@PathVariable int iid, Integer status) {
		int tid=attachmentService.load(id).getProTypeId();
		if(iid==0)
		{
			attachmentService.delete(id);
		}
		else{
			attachmentService.delete(id);
			attachmentService.delete(iid);
		}
		return "redirect:/admin/topic/showVideo/"+tid+".do";
	}

	@RequestMapping(value = "/add.do", method = RequestMethod.GET)
	public String add(Model model) {
		Topic t = new Topic();
		t.setPublishDate(new Date());
		TopicDto td = new TopicDto(t);
		model.addAttribute("topicDto", td);
		return "topic/add";
	}

	@RequestMapping(value = "/add.do", method = RequestMethod.POST)
	public String add(@Validated TopicDto topicDto, BindingResult br,
			String[] aks, Integer[] aids, HttpSession session) {
		if (br.hasErrors()) {
			return "topic/add";
		}
		Topic t = topicDto.getTopic();
		User loginUser = (User) session.getAttribute("loginUser");
		StringBuffer keys = new StringBuffer();
		if (aks != null) {
			for (String k : aks) {
				keys.append(k).append("|");
				keywordService.addOrUpdate(k);
			}
		}
		t.setKeyword(keys.toString());
		topicService.add(t, topicDto.getCid(), loginUser.getId(), aids);
//		if (topicDto.getStatus() == 1
//				&& topicService.isUpdateIndex(topicDto.getCid())) {
//			indexService.generateNewpic();
//			indexService.generateBody();
//		}
		indexService.generateBody();
		return "redirect:/jsp/common/addSuc.jsp";
	}

	// updateUI界面，准备数据
	@RequestMapping(value = "/update/{id}.do", method = RequestMethod.GET)
	@AuthMethod(role = "ROLE_PUBLISH")
	public String update(@PathVariable int id, Model model) {
		Topic t = topicService.load(id);
		String keyword = t.getKeyword();
		if (keyword != null && !"".equals(keyword.trim()))
			model.addAttribute("keywords", keyword.split("\\|"));
		// model.addAttribute("atts",attachmentService.listByTopic(id));
		TopicDto td = new TopicDto(t, t.getChannel().getId());
		model.addAttribute("topicDto", td);
		model.addAttribute("cname", t.getChannel().getName());
		return "topic/update";
	}

	// update操作完入库
	@RequestMapping(value = "/update/{id}.do", method = RequestMethod.POST)
	public String update(@PathVariable int id, @Validated TopicDto topicDto,
			BindingResult br, String[] aks, Integer[] aids, HttpSession session) {
		if (br.hasErrors()) {
			return "topic/update";
		}
		Topic tt = topicService.load(id);
		Topic t = topicDto.getTopic();
		StringBuffer keys = new StringBuffer();
		if (aks != null) {
			for (String k : aks) {
				keys.append(k).append("|");
				keywordService.addOrUpdate(k);
			}
		}
		tt.setKeyword(keys.toString());
//		tt.setChannelPicId(t.getChannelPicId());
		tt.setContent(t.getContent());
		tt.setPublishDate(t.getPublishDate());
		tt.setRecommend(t.getRecommend());
		tt.setStatus(t.getStatus());
		tt.setSummary(t.getSummary());
		tt.setTitle(t.getTitle());
		tt.setLink(t.getLink());
		tt.setLinkName(t.getLinkName());
		topicService.update(tt, topicDto.getCid(), aids);
//		if (topicService.isUpdateIndex(topicDto.getCid())) {
//			indexService.generateNewpic();
//			indexService.generateBody();
//		}
		indexService.generateBody();
		return "redirect:/jsp/common/addSuc.jsp";
	}

	// 显示文章，显示已发布文章的所有信息
	@RequestMapping("/{id}.do")
	public String show(@PathVariable int id, Model model) {
		model.addAttribute(topicService.load(id));
		// model.addAttribute("atts",attachmentService.listByTopic(id));
		return "topic/show";
	}

	@RequestMapping(value = "/searchKeyword.do")
	@AuthMethod(role = "ROLE_PUBLISH")
	public @ResponseBody
	List<String> searchKeyword(String term) {
		return keywordService.listKeywordStringByCon(term);
	}

	
	// 2014-1-21补充完善
	@RequestMapping("/treeTAll.do")
	public @ResponseBody
	List<ChannelTree> tree(HttpSession session) {
//		boolean isAdmin = (Boolean) session.getAttribute("isAdmin");
//		User loginUser = (User) session.getAttribute("loginUser");
//		if (isAdmin)
//			return channelService.generateTTree();
//		else
//			return groupService.generateUserChannelTree(loginUser.getId());
		return channelService.generateTTree();
	}
}
